import grpc
import logging
from concurrent import futures
import os
import signal
import sys
from api.grpc.service.student_service import StudentGRPCService
from api.grpc.interceptor.exception_interceptor import GlobalExceptionInterceptor
from generated import student_pb2_grpc
from config import settings

logging.basicConfig(level=logging.INFO)
logger = logging.getLogger(__name__)


class GRPCServer:
    """gRPC服务器管理类"""

    def __init__(self, host='[::]', port=50051):
        self.host = host
        self.port = port
        self.server = None

    def start(self):
        """启动gRPC服务器"""
        # 创建带有全局异常拦截器的服务器
        self.server = grpc.server(
            futures.ThreadPoolExecutor(max_workers=10),
            interceptors=[GlobalExceptionInterceptor()]
        )

        # 注册服务
        student_pb2_grpc.add_StudentServiceServicer_to_server(
            StudentGRPCService(), self.server
        )

        # 绑定端口
        address = f'{self.host}:{self.port}'
        self.server.add_insecure_port(address)

        # 启动服务器
        self.server.start()
        logger.info(f"gRPC server started on {address}")

        # 注册信号处理器,捕获进程的中断（SIGINT）和终止（SIGTERM）信号
        signal.signal(signal.SIGINT, self._signal_handler)
        signal.signal(signal.SIGTERM, self._signal_handler)

        return self.server

    def stop(self):
        """停止gRPC服务器"""
        if self.server:
            logger.info("Stopping gRPC server...")
            self.server.stop(0)
            logger.info("gRPC server stopped")

    def wait_for_termination(self):
        """等待服务器终止"""
        if self.server:
            self.server.wait_for_termination()

    def _signal_handler(self, signum, frame):
        """信号处理器"""
        logger.info(f"Received signal {signum}, shutting down...")
        self.stop()
        sys.exit(0)


def create_grpc_server():
    """创建并启动gRPC服务器"""
    # 从配置文件获取
    grpc_host = settings.grpc_host if hasattr(settings, 'grpc_host') else '[::]'
    grpc_port = settings.grpc_port if hasattr(settings, 'grpc_port') else 50051

    server = GRPCServer(host=grpc_host, port=grpc_port)
    return server


if __name__ == '__main__':
    server = create_grpc_server()
    server.start()
    server.wait_for_termination()
